<template>
  <Modal v-model="visible" title="新增用户">
    <Form
      ref="formInline"
      :model="userData"
      :rules="ruleInline"
      :label-width="70"
    >
      <FormItem prop="nickname" label="用户名">
        <i-input type="text" v-model="userData.nickname" placeholder="Username">
        </i-input>
      </FormItem>
      <FormItem prop="email" label="邮箱">
        <i-input v-model="userData.email" placeholder="email"> </i-input>
      </FormItem>
      <FormItem prop="password" label="密码">
        <i-input
          type="password"
          v-model="userData.password"
          placeholder="Password"
        >
        </i-input>
      </FormItem>
    </Form>
    <template #footer>
        <Button type="primary" @click="handleCancel"
              >返回</Button>
        <Button type="primary" @click="handleAdd"
              >注册</Button>
    </template>
  </Modal>
</template>
  <script>
export default {
  name: "AddUser",
  model: {
    prop: "open",
    event: "change",
  },
  props: {
    open: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    open: {
      handler: function (val) {
        this.visible = val;
      },
    },
    visible: {
      handler: function (val) {
        this.$emit("change", val);
      },
    },
  },
  data() {
    return {
      visible: false,
      userData: {
        nickname: "",
        email: "",
        gender: -1,
        password: "",
      },
      ruleInline: {
        nickname: [
          {
            required: true,
            message: "Please fill in the nickname.",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "Please fill in the user email",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "Please fill in the password.",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    handleAdd() {
      this.$refs.formInline.validate((valid) => {
        if (valid) {
          this.$API
            .POST_ADD_USER(this.userData)
            .then((res) => {
              this.$Message.info(res);
            })
            .catch((err) => {
              console.log(err);
            })
            .finally(() => {
                this.visible = false
              this.$emit("reload");
            });
        } else {
          this.$Message.error("Fail!");
        }
      });
    },
    handleCancel() {
        this.visible = false
    }
  },
};
</script>
  